package com.djx.comm.util;

import sun.nio.ch.FileChannelImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.CRC32;

/**
 * 文件工具
 *
 * @author dingjunxiong
 * @date 2022/04/03
 */
public class FileUtils {
    /**
     * 计算大文件 md5获取getMD5(); SHA1获取getSha1() CRC32获取 getCRC32()
     */
    private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 字节 转换为B KB MB GB
     *
     * @param size 字节大小
     * @return
     */
    public static String getPrintSize(long size) {
        long rest = 0;
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size /= 1024;
        }

        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            rest = size % 1024;
            size /= 1024;
        }

        if (size < 1024) {
            size = size * 100;
            return String.valueOf((size / 100)) + "." + String.valueOf((rest * 100 / 1024 % 100)) + "MB";
        } else {
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
        }
    }

    /**
     * 对一个文件获取md5值
     *
     * @return md5串
     * @throws NoSuchAlgorithmException
     */
    public static String getMD5(File file) throws IOException, NoSuchAlgorithmException {
        //信息摘要
        MessageDigest messagedigest = MessageDigest.getInstance("MD5");
        try (
                FileInputStream in = new FileInputStream(file);
                FileChannel ch = in.getChannel()
        ) {
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            messagedigest.update(byteBuffer);
            try {
                Method method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
                method.setAccessible(true);
                method.invoke(FileChannelImpl.class, byteBuffer);
            } catch (Exception e) {
                throw new IOException("获取md5值:" + e.getMessage());
            }
        } catch (Exception e) {
            throw new IOException("getMD5:" + e.getMessage());
        }
        return bufferToHex(messagedigest.digest());
    }

    /***
     * 计算SHA1码
     *
     * @return String 适用于上G大的文件
     * @throws NoSuchAlgorithmException
     */
    public static String getSha1(File file) throws OutOfMemoryError, IOException, NoSuchAlgorithmException {
        //信息摘要
        MessageDigest messagedigest = MessageDigest.getInstance("SHA-1");
        try (
                FileInputStream in = new FileInputStream(file);
                FileChannel ch = in.getChannel()
        ) {
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            messagedigest.update(byteBuffer);
            Method method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
            method.setAccessible(true);
            method.invoke(FileChannelImpl.class, byteBuffer);
        } catch (Exception e) {
            // TODO: handle exception
            throw new IOException("getSha1:" + e.getMessage());
        }
        return bufferToHex(messagedigest.digest());
    }

    /**
     * 获取文件CRC32码
     *
     * @return String
     */
    public static String getCRC32(File file) throws IOException {
        CRC32 crc32 = new CRC32();
        try (
                FileInputStream fileInputStream = new FileInputStream(file);
        ) {
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                crc32.update(buffer, 0, length);
            }
            return crc32.getValue() + "";
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("getCRC32:" + e.getMessage());
        } catch (IOException e) {
            throw new IOException("getCRC32:" + e.getMessage());
        }
    }

    /**
     * @return String
     * @Description 计算二进制数据
     */
    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    /**
     * 计算二进制
     *
     * @param bytes
     * @param m
     * @param n
     * @return
     */
    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    /**
     * 计算二进制
     *
     * @param bt
     * @param stringbuffer
     */
    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}
